package avicit.bdp.dcs.stream.utils;

import avicit.bdp.common.dto.request.dds.ProcessSchedulerDto;
import avicit.bdp.dcs.job.dto.JobDTO;
import avicit.bdp.dcs.semistructure.dto.IotdbJsonDto;
import avicit.bdp.dcs.semistructure.utils.Constants;
import avicit.bdp.dcs.stream.dto.KafkaJsonDto;
import avicit.bdp.dcs.stream.dto.MeasureParaDto;
import avicit.bdp.dcs.stream.dto.MsgTemplateDto;
import avicit.bdp.dcs.task.dto.TaskDTO;
import avicit.bdp.dcs.tools.enums.SyncStatus;
import avicit.platform6.core.rest.msg.ResponseMsg;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

public class TestUtils {
    private static RestTemplate restTemplate  = new RestTemplate();

    /**
     * 保存数据源
     */
    public static HttpEntity<String> buildSaveDataSourceParas(int jobType, String jobName,
                                                              String srcDsId, String dstDsId) {
        JobDTO jobDTO = new JobDTO();
        jobDTO.setJobType(jobType);
        jobDTO.setName(jobName);
        jobDTO.setSrcDatasourceId(srcDsId);
        jobDTO.setDstDatasourceId(dstDsId);

        String param = JSONObject.toJSONString(jobDTO);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<>(param, headers);
    }

    /**
     * 保存表映射关系参数
     */
    public static HttpEntity<String> buildSaveTblMapping(int jobType, String jobId,
                                                         String srcTblName, String dstTbleName) {
        JobDTO jobDTO = new JobDTO();
        jobDTO.setId(jobId);
        jobDTO.setTransferType("1,2");
        jobDTO.setProcessMode(1);
        jobDTO.setSelectedTable("[{\"src_table\":\"" + srcTblName+ "\",\"dst_table\":\"" + dstTbleName + "\"}]");
        jobDTO.setSelectedFile(srcTblName);

        KafkaJsonDto kafkaJsonDto = new KafkaJsonDto();
        kafkaJsonDto.setTopics("json");
        kafkaJsonDto.setKafkaPartitions("0");
        kafkaJsonDto.setMsgId("xxxxxx");
        kafkaJsonDto.setMsgAgreement("json");
        kafkaJsonDto.setMsgTemplate("event.deviceId");
        jobDTO.setKafkaJson(JSONObject.toJSONString(kafkaJsonDto));

        // 数据同步
        if (jobType == 5) {
            jobDTO.setTableInit(1);
            jobDTO.setJobType(5);
        }

        String param = JSONObject.toJSONString(jobDTO);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<String>(param, headers);
    }

    /**
     * 任务配置检查
     */
    public static HttpEntity<String> buildCheckTaskConfig(String jobId) {
        JobDTO jobDTO = new JobDTO();
        jobDTO.setId(jobId);
        String param = JSONObject.toJSONString(jobDTO);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<String>(param, headers);
    }

    /**
     * 保存预检查参数
     */
    public static HttpEntity<String> buildPreChecks(String jobId) {
        JobDTO jobDTO = new JobDTO();
        jobDTO.setId(jobId);
        String param = JSONObject.toJSONString(jobDTO);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<String>(param, headers);
    }

    /**
     * 获取taskId
     */
    public static HttpEntity<String> buildUpdateTask(String taskId) {
        TaskDTO taskDTO = new TaskDTO();
        taskDTO.setId(taskId);
        taskDTO.setModifyColumn(0);
        IotdbJsonDto iotdbJsonDto = new IotdbJsonDto();
        iotdbJsonDto.setEmptyLineProcess(1);
        iotdbJsonDto.setTimeseries("root.182.liubf1");
        taskDTO.setIotdbJsonDto(iotdbJsonDto);
        String param = JSONObject.toJSONString(taskDTO);
        HttpHeaders headers11 = new HttpHeaders(); // 创建一个头部对象
        headers11.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers11.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers11.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<String>(param, headers11);
    }

    /**
     * 保存Job状态
     */
    public static HttpEntity<String> buildUpdateJobStatus(String jobId) {
        JobDTO jobDTO = new JobDTO();
        jobDTO.setId(jobId);
        jobDTO.setJobStatus(SyncStatus.NOT_STARTED.getCode());
        String param = JSONObject.toJSONString(jobDTO);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<String>(param, headers);
    }

    /**
     * 启动Job
     */
    public static HttpEntity<String> buildStartJob(String jobId) {
        JobDTO jobDTO = new JobDTO();
        jobDTO.setId(jobId);
        String param = JSONObject.toJSONString(jobDTO);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<String>(param, headers);
    }

    /**
     * 启用Job
     */
    public static HttpEntity<String> buildReleaseJob(String jobId) {
        JobDTO jobDTO = new JobDTO();
        jobDTO.setId(jobId);
        jobDTO.setEnable(1);
        String param = JSONObject.toJSONString(jobDTO);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<String>(param, headers);
    }

    /**
     * 删除Job
     */
    public static HttpEntity<String> buildDeleteJob(String jobId) {
        JobDTO jobDTO = new JobDTO();
        jobDTO.setId(jobId);
        String param = JSONObject.toJSONString(jobDTO);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<String>(param, headers);
    }

    /**
     * Get方法需要的HttpEntity
     */
    public static HttpEntity<String> buildGetHttpEntity() {
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<String>(null, headers);
    }

    /**
     * 保存定时信息
     */
    public static HttpEntity<String> buildSaveScheduleHttpEntity(String jobId) {
        ProcessSchedulerDto processSchedulerDto = new ProcessSchedulerDto();
        processSchedulerDto.setProcessDefinitionId(jobId);
        processSchedulerDto.setCrontab("0 0/1 * * * ?");// 从当前时间每隔2min执行一次
        Date currDate = new Date();
        long uninxCurrDate = currDate.getTime();
        processSchedulerDto.setStartTime(new Date(uninxCurrDate - 60* 1000));// 当前时间前1mmin
        processSchedulerDto.setEndTime(new Date(uninxCurrDate + 10 * 60* 1000));//当前时间后10min
        processSchedulerDto.setFailureStrategy(1);

        String param = JSONObject.toJSONString(processSchedulerDto);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));

        return new HttpEntity<String>(param, headers);
    }

    /**
     * 获取创建的JobId
     */
    public static String getJobId(String jobId) {
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        ResponseEntity<ResponseMsg> result = restTemplate.exchange(Constants.DCS_HOSTPORT + "/api/bdp/dcs/job/JobRest" +
                        "/getJobList" +
                        "?jobStatus&sort&name=processTest1&jobType=1&currentPage=1&pageSize=10",
                HttpMethod.GET, buildGetHttpEntity(), ResponseMsg.class);

        ResponseMsg body = result.getBody();
        LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>)body.getResponseBody();
        List<Object> finalBody = (List<Object>) map.get("result");
        for (Object obj : finalBody) {
            LinkedHashMap<String, String> jobObj = (LinkedHashMap<String, String>)obj;
            JobDTO jobInfo = JSON.parseObject(JSON.toJSONString(jobObj), JobDTO.class);
            if (jobInfo.getName().equals("processTest1")) {
                jobId = jobInfo.getId();

                return jobId;
            }
        }
        return null;
    }

    public static HttpEntity<String> buildSaveTemplateParas() {
        MsgTemplateDto msgTemplateDto = new MsgTemplateDto();
        msgTemplateDto.setDeviceId("069829f0-4a3f-4200-8276-f1167931add0");
        msgTemplateDto.setDeviceName("虚拟设备2");
        String param = JSONObject.toJSONString(msgTemplateDto);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));

        return new HttpEntity<String>(param, headers);
    }

    public static HttpEntity<String> buildDeleteMsgTemplateParas(String id) {
        MsgTemplateDto msgTemplateDto = new MsgTemplateDto();
        msgTemplateDto.setId(id);
        String param = JSONObject.toJSONString(msgTemplateDto);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));

        return new HttpEntity<String>(param, headers);
    }

    public static HttpEntity<String> buildaddMsgTemplateParas(MeasureParaDto measureParaDto, String msgTemplateId) {
        MsgTemplateDto msgTemplateDto = new MsgTemplateDto();
        msgTemplateDto.setId(msgTemplateId);
        List<MeasureParaDto> measureParaDtos = new ArrayList<>();
        measureParaDtos.add(measureParaDto);
        msgTemplateDto.setMeasureParaDtoList(measureParaDtos);
        String param = JSONObject.toJSONString(msgTemplateDto);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));

        return new HttpEntity<String>(param, headers);
    }

    public static HttpEntity<String> buildUpdateTaskParam(String taskId, String srcTable, String dstTable) {
        TaskDTO taskDTO = new TaskDTO();
        taskDTO.setId(taskId);
        taskDTO.setModifyColumn(1);
        taskDTO.setMappingColumn("[{\"templateId\":\"" + srcTable + "\",\"tableName\":\"" + dstTable + "\"," +
                "\"templateName\":\"虚拟设备2\"," +
                "\"columnList\":[{\"srcColumnName\":\"Device_Temperature\",\"srcColumnType\":\"double\"," +
                "\"srcColumnPrefix\":\"event.metadata\",\"dstColumnName\":\"device_temperature\"," +
                "\"dstColumnType\":\"string\",\"desensitizationPolicyId\":\"\",\"desensitizationRuleId\":\"\"}]}]");
        String param = JSONObject.toJSONString(taskDTO);

        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));

        return new HttpEntity<String>(param, headers);
    }

    public static HttpEntity<String> buildUpdateIotdbTaskParam(String taskId, String srcTable, String dstTable) {
        TaskDTO taskDTO = new TaskDTO();
        taskDTO.setId(taskId);
        taskDTO.setModifyColumn(1);
        taskDTO.setMappingColumn("[{\"templateId\":\"" + srcTable + "\",\"tableName\":\"" + dstTable + "\"," +
                "\"templateName\":\"虚拟设备2\"," +
                "\"columnList\":[{\"srcColumnName\":\"Device_Temperature\",\"srcColumnType\":\"double\"," +
                "\"srcColumnPrefix\":\"event.metadata\",\"dstColumnName\":\"device_temperature\"," +
                "\"dstColumnType\":\"TEXT\",\"desensitizationPolicyId\":\"\",\"desensitizationRuleId\":\"\"}]}]");
        String param = JSONObject.toJSONString(taskDTO);

        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));

        return new HttpEntity<String>(param, headers);
    }
}
